package com.base.test.dao.shardingtype.table;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;
/**
 * @title 自定义Hash取模分表策略
 * @author carl
 * @createDate 2019-11-22
 */
@Slf4j
public class PreciseLongModuloShardingTableAlgorithm implements PreciseShardingAlgorithm<Long> {
    @Override
    public String doSharding(final Collection<String> allTableNames, final PreciseShardingValue<Long> preciseShardingValue) {
        log.debug("name hashCode取模 分表规则计算开始 . 请求参数 : {}" , preciseShardingValue.getValue());
        int size = allTableNames.size();
        for (String name  : allTableNames) {//计算hashCode绝对值
           // int shardingHash = Math.abs(preciseShardingValue.getValue().hashCode()); //计算hashCode绝对值
            if (name.endsWith(preciseShardingValue.getValue() % size + "")) {//根据hashCode值对分表的size取模
                log.debug("name hashCode取模 分表规则匹配成功 . hashCode值 : {} , 取模值 : {} , 匹配的表 : {}"  , preciseShardingValue.getValue() % size  , name);
                return name;
            }
        }
        throw new UnsupportedOperationException();
    }
}
